package com.dongjiantong.web.protal.controller.farmrecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.model.Stables;
import com.dongjiantong.biz.service.FarmStockService;
import com.dongjiantong.biz.service.StablesService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.model.FarmRecordsProduction;
import com.dongjiantong.farmrecords.service.FarmRecordsProductionService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.sys.enums.AnimalTypeEnum;
import com.dongjiantong.sys.model.AnimalType;
import com.dongjiantong.sys.service.AnimalTypeService;
import com.dongjiantong.user.model.UserArea;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.*;

/**
 * 生产中心-生产记录(政府端)
 */

@Slf4j
@OpenBean
public class FarmRecordsProductionController {

    @Reference(version = "1.0.0")
    public FarmRecordsProductionService farmRecordsProductionService;
    @Reference(version = "1.0.0")
    public StablesService stablesService;
    @Reference(version = "1.0.3")
    public AnimalTypeService animalTypeService;
    @Reference(version = "1.0.0")
    public FarmStockService farmStockService;

    /**
     * 根据养殖场ids,起止时间或者状态查询生产记录 (条件都可以为空,表示查询所有)
     * @param areaList 请求的地区List
     * @param farmId  请求的养殖场id
     * @param startDate 请求的查询开始时间
     * @param endDate   请求的查询结束时间
     * @param pageNum
     * @param pageSize
     * @param breedType   请求的畜种
     * @return  Response<PageInfo<FarmRecordsDisinfect>>
     */
    @OpenMethod(key = "web.farmrecordsproduction.selectByFarmIdAndDate",
            paramNames = {"areaList","farmId","startDate","endDate","pageNum","pageSize","breedType"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsProduction>> selectByFarmIdAndDate(List<Integer> areaList,
                                                                                                        @RequestParam(required = false) Long farmId,
                                                                                                        @RequestParam(required = false) String startDate,
                                                                                                        @RequestParam(required = false) String endDate,
                                                                                                        @RequestParam(required = false) Integer pageNum,
                                                                                                        @RequestParam(required = false) Integer pageSize,
                                                                                                        @RequestParam(required = false) List<Integer> breedType){
        if (farmRecordsProductionService == null){
            throw new OPServerException("请检查 farmRecordsProductionService 服务");
        }

        Map map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }else {
            //如果养殖场id为空,判断地区code是否为空,不为空则根据地区查询,否则查询登陆人管辖范围的记录
            if (areaList.size() > 0){
                int i = 0;
                for (Integer areaCode : areaList) {
                    if (i == 0) {
                        map.put("province_id",areaCode);
                    } else if (i == 1) {
                        map.put("city_id",areaCode);
                    } else if (i == 2) {
                        map.put("region_id",areaCode);
                    } else if (i == 3) {
                        map.put("street_id",areaCode);
                    } else {
                        map.put("village_id",areaCode);
                    }
                    i++;
                }
            }
        }
        if (!Strings.isNullOrEmpty(startDate)){
            Date startDate1 = new Date(Long.valueOf(startDate));
            map.put("startDate",startDate1);
        }
        if (!Strings.isNullOrEmpty(endDate)){
            Date endDate1 = new Date(Long.valueOf(endDate));
            map.put("endDate",endDate1);
        }
        map.put("status", FarmRecordsNumberStatus.SUBMIT.getCode());
        if (breedType.size() > 0){
            switch (breedType.size()){
                case 1:
                    map.put("breed_type",breedType.get(0));
                    break;
                case 2:
                    map.put("breed_second_type",breedType.get(1));
                    break;
                case 3:
                    map.put("breed_third_type",breedType.get(2));
                default:
                    break;
            }
        }

        //这里查询除牛之外的其他动物
        map.put("animal_second_non_bull",AnimalTypeEnum.BULL.getCode());

        PageInfo<FarmRecordsProduction> farmRecordsProductionPageInfo = farmRecordsProductionService.selectByMap(pageNum,pageSize,map);
        return Response.ok(farmRecordsProductionPageInfo);
    }



    /**
     * 根据主键id查询对应生产记录
     * @param id
     * @return
     */
    @OpenMethod(key = "web.farmrecordsproduction.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsProduction> selectById(@RequestParam(required = false)Long id){
        if (id == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "请求的id不能为空");
        }
        try {
            if (farmRecordsProductionService == null){
                throw new OPServerException("请检查 farmRecordsProductionService 服务");
            }

            FarmRecordsProduction farmRecordsProduction = farmRecordsProductionService.selectByPrimaryKey(id);
            if (farmRecordsProduction == null){
                return Response.fail(HttpCode.INTERNAL_SERVER_ERROR,"查无数据");
            }
            return Response.ok(farmRecordsProduction);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(e.getMessage());
        }
    }

    /**
     * 根据主键id删除对应生产记录
     * @param id
     * @return
     */
    @OpenMethod(key = "web.farmrecordsproduction.deleteById",
            paramNames = {"id"},
            httpMethods = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class, RuntimeException.class})
    public Response<Boolean> deleteById(@RequestParam(required = false)Long id){
        if (id == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "请求id不能为空");
        }
        try {
            if (farmRecordsProductionService == null){
                throw new OPServerException("farmRecordsProductionService 为null,请检查");
            }

            FarmRecordsProduction farmRecordsProduction = new FarmRecordsProduction();
            farmRecordsProduction.setId(id);
            farmRecordsProduction.setDelete_flag(FarmRecordsNumberStatus.INVALID.getCode());
            farmRecordsProduction.setUpdated_at(new Date());

            Integer con = farmRecordsProductionService.updateByPrimaryKeySelective(farmRecordsProduction);

            //if (farmRecordsProduction.getStable_id() != null){
                Stables stables = new Stables();
                stables.setId(farmRecordsProduction.getStable_id());
                stables.setFarm_id(farmRecordsProduction.getFarm_id());
                stables.setUpdated_at(new Date());
                //todo 更新栏舍存栏数

                stablesService.updateByPrimaryKeySelective(stables);
            //}
            Map<String,Object> map = Maps.newHashMap();
            map.put("farmId",farmRecordsProduction.getFarm_id());
            map.put("changeQuantity",farmRecordsProduction.getChange_quantity());
            farmStockService.updateByFarmId(map);

            return Response.ok(con == 0 ? false : true);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_DELETE_FAIL,HttpCode.DATA_DELETE_FAIL.getMessage());
        }
    }
}
